<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 类别table start-->
      <div class="list">
        <!-- 数据总计区域 start -->
        <div v-show="!listLoading" class="pagination-container">
          <div style="margin-right: 10px;margin-bottom: 10px;float:left;color:rgb(44,162,252);padding-top: 7px;font-size: 14px">
            数据总计: {{ total }} (条)
          </div>
          <el-button size="small" style="margin-bottom: 10px;float:right" type="primary" @click="add()">添加</el-button>
        </div>
        <!-- 数据总计区域 end -->
        <!--列表 start-->
        <el-table
          v-loading.body="listLoading"
          border
          ref="multipleTable"
          :data="list"
          tooltip-effect="dark"
          style="width: 100%;"
          @selection-change="handleSelectionChange">

          <el-table-column
            type="selection"
            width="55"
            align="center">
          </el-table-column>
          <el-table-column
            prop="user_name"
            label="用户名"
            min-width="220"
            align="center"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色"
            min-width="220"
            align="center">
            <template slot-scope="scope">
              <el-tag type="warning" v-if="scope.row.role === 1">{{ scope.row.role_name }}</el-tag>
              <el-tag v-else>{{ scope.row.role_name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            min-width="220"
            align="center"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button type="success" size="small" v-if="scope.row.status === 1" @click="changeStatus(scope.row.id, scope.row.status)">正常</el-button>
              <el-button type="danger" size="small" v-else @click="changeStatus(scope.row.id, scope.row.status)">禁用</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="上一次登录时间" width="200" align="center">

          </el-table-column>
          <el-table-column
            prop=""
            label="操作"
            show-overflow-tooltip
            min-width="220"
            align="center">
            <template slot-scope="scope">
              <!--<span v-if="actionNode.indexOf('change') >= 0 || actionNode['all'] == 1">-->
                <el-button type="warning" size="small" @click="update(scope.$index)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteDialog(scope.row.id)">删除</el-button>
                <!--<el-button type="warning" size="small" v-else="scope.row.status === 1" @click="updateModel(scope.$index)">变更</el-button>-->
              <!--</span>-->
            </template>
          </el-table-column>
        </el-table>
        <!--列表 end-->
      </div>
      <!-- 分页区域 start -->
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                       :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <!-- 分页区域 end -->
      <!-- 类别table end-->
    </div>
    <!-- 添加管理员 start -->
    <el-dialog :title="modelText[status]" :visible.sync="formStatus" v-loading.fullscreen.lock="dialogLoading">
      <el-form :model="formData" :rules="rules" ref="formData">
        <el-form-item label="" v-show="showPass">
          <el-alert :closable="false" align='center' title="若不写密码--初始密码为CDZ123456" type="info" show-icon v-if="status === 'create'"></el-alert>
          <!--<el-alert :closable="false" align='center' title="若不修改密码，不需要填写" type="info" show-icon v-else></el-alert>-->
        </el-form-item>

        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model.trim="formData.username" placeholder="请输入2~20位字母或数字" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="职务" :label-width="formLabelWidth" prop="role">
          <el-select v-model="formData.role" filterable allow-create placeholder="请选择职务" style="width: 100%;">
            <el-option v-for="item in duties" :key="item.id" :label="item.role" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="昵　　称" :label-width="formLabelWidth" prop="name">
          <el-input v-model.trim="formData.name" placeholder="请输入昵称" auto-complete="off"></el-input>
        </el-form-item>


        <el-row v-if="status === 'create'">

            <el-form-item label="密　　码" :label-width="formLabelWidth" prop="password">
              <el-input v-model.trim="formData.password" auto-complete="off" type="password" placeholder="请输入您的密码" clearable></el-input>
            </el-form-item>

            <el-form-item label="确认密码" :label-width="formLabelWidth" prop="checkPassword">
              <el-input v-model.trim="formData.checkPassword" auto-complete="off" type="password"
                        placeholder="请再次输入您的密码" clearable></el-input>
            </el-form-item>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formStatus = false">取 消</el-button>
        <el-button type="primary" v-if="status === 'create'" @click="create()">确 定</el-button>
        <el-button type="primary" v-else @click="editor()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加管理员 end -->
  </div>
</template>
<script>
import { adminList, getDuties, createAdmin, updateAdmin, deleteAdmin, changeStatus } from '@/api/admin'
export default {
  data() {
    // 验证密码
    var passwordCheck = (rule, value, callback) => {
      if (value === '' && this.formData.password === '' && this.status === 'create') {
        this.formData.password = 'CDZ123456'
        this.formData.checkPassword = 'CDZ123456'
        callback()
      } else if (value === '' && this.formData.password === '' && this.status === 'update') {
        callback()
      } else if (value !== this.formData.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      /** 基本变量 **/
      listQuery: { // 列表请求数据
        page: 1,
        limit: 10, // 每页显示10条
        where: {
          status: '' // 状态
          // department_id: '', // 部门搜索
          // roles_id: '', // 职务搜索
          // guid: '' // 员工guid
        }
      },
      list: [],
      total: 0,
      listLoading: false,
      multipleSelection: [],
      /** dialog验证 **/
      rules: { // 创建员工的验证条件
        username: [
          { required: true, message: '输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择职务', trigger: 'blur' }
        ],
        password: [
          { min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'blur' }
        ],
        checkPassword: [
          { min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'blur' },
          { validator: passwordCheck, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ]
      },
      /** 新建管理员 **/
      formLabelWidth: '120px',
      showPass: true,
      dialogLoading: false,
      formStatus: false,
      status: 'create',
      modelText: {
        'create': '添加',
        'update': '编辑'
      },
      formData: {
        username: '',
        role: '',
        password: '',
        checkPassword: '',
        id: '',
        name: ''
      },
      duties: []
    }
  },
  methods: {
    /** 获取列表数据 **/
    fetchList() {
      // 开启加载层
      this.listLoading = true
      adminList(this.listQuery).then(response => {
        // 当page不等于1时 判断返回数组是否为空
        if (!response.data && this.listQuery.page !== 1) {
          // 当前页－1
          this.listQuery.page = this.listQuery.page - 1
          // 重新获取数据
          this.fetchList()
        } else {
          // 添加列表数据
          this.list = response.data
          // 设置总条数
          this.total = response.count
          // 关闭 加载层
          this.listLoading = false
        }
      })
    },
    /** 新建管理员窗口 **/
    add() {
      this.status = 'create'
      this.formStatus = true
      this.clear()
      for (var i in this.formData) {
        this.formData[i] = ''
      }
      // 获取职务列表
      this.getDuties()
    },
    /** 新建管理员 **/
    create() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          // 创建
          createAdmin(this.formData).then(response => {
            this.$notify.success({
              title: '信息提示',
              message: '添加成功',
              duration: 3000
            })
            this.formStatus = false
            this.listLoading = false
            this.fetchList()
          }).catch(() => {
            this.listLoading = false
          })
        }
      })
    },
    /** 获取职务列表 **/
    getDuties() {
      getDuties({}).then(response => {
        this.duties = response
      })
    },
    /** 编辑管理员 **/
    update(index) {
      this.status = 'update'
      this.getDuties()
      this.formData.username = this.list[index].username
      this.formData.role = this.list[index].role
      this.formData.id = this.list[index].id
      this.formData.name = this.list[index].name
      this.formData.password = ''
      this.formData.checkPassword = ''
      this.formStatus = true
    },
    /** 编辑管理员 **/
    editor() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          this.formStatus = true
          // 编辑
          updateAdmin(this.formData).then(response => {
            this.$notify.success({
              title: '信息提示',
              message: response,
              duration: 3000
            })
            this.formStatus = false
            this.listLoading = false
            this.fetchList()
          }).catch(() => {
            this.listLoading = false
          })
        }
      })
    },
    /** 删除管理员 **/
    deleteDialog(id) {
      this.$confirm('确认删除该用户吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAdmin({ id: id, is_del: 2 }).then(response => {
          this.$notify.success({
            title: '信息提示',
            message: '删除成功',
            duration: 3000
          })
          this.fetchList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /** 修改状态 **/
    changeStatus(id, stauts) {
      changeStatus({ id: id, status: stauts }).then(response => {
        this.$notify.success({
          title: '信息提示',
          message: response,
          duration: 3000
        })
        this.fetchList()
      })
    },
    /** 置空数据 **/
    clear() {
      if (this.$refs['formData']) {
        this.$refs['formData'].resetFields()
      }
    },
    // 选择操作
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 自定义显示条数
    handleSizeChange(value) {
      // 重新定义每页显示几条
      this.listQuery.page = 1
      this.listQuery.limit = value
      this.fetchList()
    },
    // 页数跳转
    handleCurrentChange(value) {
      this.listQuery.page = value
      this.fetchList()
    }
  },
  // 页面第一次执行
  mounted() {
    this.fetchList()
  }
}

</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 110px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
